package com.cykj.pos.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.cykj.common.core.domain.AjaxResult;
import com.cykj.common.core.domain.entity.SysUser;
import com.cykj.common.utils.SecurityUtils;
import com.cykj.pos.domain.*;
import com.cykj.pos.domain.dto.BizAgentidAppkeyDTO;
import com.cykj.pos.mapper.BizPosMachineMapper;
import com.cykj.pos.mapper.BizWithdrawalRecordsMapper;
import com.cykj.pos.pojo.BatchPayment;
import com.cykj.pos.pojo.BatchPaymentList;
import com.cykj.pos.pojo.UserSign;
import com.cykj.pos.service.*;
import com.cykj.pos.util.HqyApiUtilsV2;
import com.cykj.pos.util.HqyMerFunctionEnumsV2;
import com.cykj.pos.util.IdGen;
import com.cykj.system.domain.WalletNew;
import com.cykj.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.commons.lang3.StringUtils;
import com.cykj.pos.mapper.BizWalletNewMapper;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Console;
import java.math.BigDecimal;
import java.util.*;

/**
 * bizWalletNewService业务层处理
 *
 * @author weijianbo
 * @date 2025-01-20
 */
@Service
public class BizWalletNewServiceImpl extends ServiceImpl<BizWalletNewMapper, BizWalletNew> implements IBizWalletNewService {

    @Resource
    private BizWalletNewMapper bizWalletNewMapper;

    @Resource
    private IBizWithdrawalRecordsService iBizWithdrawalRecordsService;

    @Resource
    private ISysUserService iSysUserService;

    @Resource
    private IBizMerchantService iBizMerchantService;

    @Resource
    private IBizMicroInfoService iBizMicroInfoService;

    @Resource
    private BizWithdrawalRecordsMapper bizWithdrawalRecordsMapper;

    @Resource
    private BizPosMachineMapper bizPosMachineMapper;

    @Resource
    private BizWithdrawalRecordsServiceImpl bizWithdrawalRecordsServiceImpl;

    @Resource
    private IBizMicroInfoService bizMicroInfoService;

    @Resource
    private  IBizMerchantReceiverService iBizMerchantReceiverService;
    @Resource
    private  PosV1AppMerApiServiceImpl posV1AppMerApiServiceimpl;
    @Resource
    private  PosPCommonParamConfig PosPCommonParamConfig;

    @Resource
    private IBizCashoutRecordsService cashoutRecordsService;


    @Override
    public List<BizWalletNew> queryList(BizWalletNew bizWalletNew) {
        LambdaQueryWrapper<BizWalletNew> lqw = Wrappers.lambdaQuery();
        if (StringUtils.isNotBlank(bizWalletNew.getUserName())){
            lqw.like(BizWalletNew::getUserName ,bizWalletNew.getUserName());
        }
        if (StringUtils.isNotBlank(bizWalletNew.getDeptName())){
            lqw.like(BizWalletNew::getDeptName ,bizWalletNew.getDeptName());
        }
        if (StringUtils.isNotBlank(bizWalletNew.getChannelName())){
            lqw.like(BizWalletNew::getChannelName ,bizWalletNew.getChannelName());
        }
        return this.list(lqw);
    }

    @Override
    public JSONObject walletBalance(BizWalletNew bizWalletNew) {
        // 渠道  , 代理id
        bizWalletNew = bizWalletNewMapper.walletBalance(bizWalletNew);
        SysUser sysUser = iSysUserService.selectUserById(bizWalletNew.getUserId());
        bizWalletNew.setPayPassword(sysUser.getPaymentPassword());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",200);
        jsonObject.put("msg","钱包");
        jsonObject.put("profitAmount",bizWalletNew.getProfitAmount());
        jsonObject.put("rewardAmount",bizWalletNew.getRewardAmount());
        jsonObject.put("payPassword",sysUser.getPaymentPassword());
        //提现分润钱包
        AizWithdrawalWallet aizWithdrawalWallet = bizWalletNewMapper.getWithdrawalWalletByUserId(bizWalletNew.getUserId(),bizWalletNew.getChannelId());
        if(aizWithdrawalWallet == null){
            jsonObject.put("withdrawalAmount",0.00);
        }else{
            jsonObject.put("withdrawalAmount",aizWithdrawalWallet.getAmount());
        }
        //扣款钱包
        AizDeductionWallet aizDeductionWallet = bizWalletNewMapper.getDeductionWalletByUserId(bizWalletNew.getUserId());
        if(aizDeductionWallet == null){
            jsonObject.put("deductionAmount",0.00);
        }else{
            jsonObject.put("deductionAmount",aizDeductionWallet.getAmount());
        }
        return jsonObject;
    }

    @Override
    public AjaxResult withdrawalMoney(BizWalletNew bizWalletNew) {
        // 渠道  , 代理id ,
        BizWalletNew bizWallet = bizWalletNewMapper.walletBalance(bizWalletNew);
        System.out.println("分润提现部门id"+bizWallet.getDeptId());
        if(bizWallet.getDeptId() == 100L){
            System.out.println(bizWallet.getUserId()+"闯业提现");
            return iBizWithdrawalRecordsService.withdrawalZb(bizWalletNew,bizWallet);
        }else{
            System.out.println(bizWallet.getUserId()+"非闯业提现");
            return executeWithdrawalBizWalletNew(bizWalletNew,bizWallet);
        }
    }

    @Override
    public BizWalletNew getWalletNewByUserId(Long userId,Long channelId) {
        BizWalletNew walletNew = bizWalletNewMapper.getWalletNewByUserId(userId,channelId);
        return walletNew;
    }

    @Override
    public AjaxResult withdrawalTemplateSaveOrUpdate(WithdrawalRateTemplate withdrawalRateTemplate) {
        if(withdrawalRateTemplate.getId() == null){
            bizWalletNewMapper.insertWithdrawalRateTemplate(withdrawalRateTemplate);
        }else{
            bizWalletNewMapper.updateWithdrawalRateTemplate(withdrawalRateTemplate);
        }
        return AjaxResult.success("保存成功");
    }

    @Override
    public AjaxResult withdrawalTemplateShowBack(WithdrawalRateTemplate withdrawalRateTemplate) {
        withdrawalRateTemplate = bizWalletNewMapper.withdrawalTemplateShowBack(withdrawalRateTemplate);
        return AjaxResult.success("回显模板",withdrawalRateTemplate);
    }

    @Override
    public AizWithdrawalWallet getWithdrawalWalletByUserId(Long userId,Long channelId) {
        return bizWalletNewMapper.getWithdrawalWalletByUserId(userId,channelId);
    }

    @Override
    public void updateAizWithdrawalWalletByUserId(AizWithdrawalWallet aizWithdrawalWallet) {
        bizWalletNewMapper.updateAizWithdrawalWalletByUserId(aizWithdrawalWallet);
    }

    @Override
    public void insertWithdrawalWallet(AizWithdrawalWallet aizWithdrawalWallet) {
        bizWalletNewMapper.insertWithdrawalWallet(aizWithdrawalWallet);
    }

    @Override
    public void insertDeductionWallet(AizDeductionWallet aizDeductionWallet) {
        bizWalletNewMapper.insertDeductionWallet(aizDeductionWallet);
    }

    @Override
    @Transactional
    public AjaxResult withdrawalAizWithdrawalMoney(AizWithdrawalWallet aizWithdrawalMoney){
        SysUser sysUser = iSysUserService.selectUserById(aizWithdrawalMoney.getUserId());
        if(sysUser.getDeptId() == 100L){
            AizWithdrawalWallet aizWithdrawalMoneyData =
                    bizWalletNewMapper.getWithdrawalWalletByUserId(aizWithdrawalMoney.getUserId(),aizWithdrawalMoney.getChannelId());
            if(aizWithdrawalMoneyData == null){
                return AjaxResult.error("暂无奖励钱包,请联系代理");
            }
            if(aizWithdrawalMoney.getAmount().compareTo(aizWithdrawalMoneyData.getAmount()) > 0){
                return AjaxResult.error("奖励账户余额不足,请重新输入");
            }
            //扣除提现金额
            aizWithdrawalMoneyData.setAmount(aizWithdrawalMoneyData.getAmount().subtract(aizWithdrawalMoney.getAmount()));
            // 保存提现记录
            BizWithdrawalRecords bizWithdrawalRecords = new BizWithdrawalRecords();
            bizWithdrawalRecords.setUserId(aizWithdrawalMoney.getUserId());
            SysUser user = iSysUserService.selectUserById(aizWithdrawalMoney.getUserId());
            bizWithdrawalRecords.setUserName(user.getNickName());
            bizWithdrawalRecords.setMerchPhone(user.getPhonenumber());
            bizWithdrawalRecords.setChannelId(aizWithdrawalMoney.getChannelId());
            BizMerchant bizMerchant = iBizMerchantService.getMerchantByUserId(aizWithdrawalMoney.getUserId());
            BizMicroInfo bizMicroInfo = iBizMicroInfoService.getBizMicroInfoByMerchId(bizMerchant.getMerchId());
            bizWithdrawalRecords.setWithdrawalName(bizMicroInfo.getMerchIdcardName());
            bizWithdrawalRecords.setWithdrawalAccount(bizMicroInfo.getMerchBankCardno());
            bizWithdrawalRecords.setWithdrawalType("3");//1 结算账户 2 机具返现 3 奖励
            bizWithdrawalRecords.setWithdrawalAmount(aizWithdrawalMoney.getAmount());
            BizChannel bizChannel = bizPosMachineMapper.getChannelByChannelId(aizWithdrawalMoney.getChannelId().toString());
            bizWithdrawalRecords.setChannelName(bizChannel.getChannelName());
            WithdrawalRateTemplate withdrawalRateTemplate = bizWithdrawalRecordsMapper.getDefaultWithdrawalRateTemplate();
            BigDecimal rate= withdrawalRateTemplate.getProfitRate();
            BigDecimal fee = withdrawalRateTemplate.getProfitFee();
            // 手续费
            BigDecimal arrivalAmount = aizWithdrawalMoney.getAmount().multiply(rate).setScale(2,BigDecimal.ROUND_DOWN).add(fee);
            bizWithdrawalRecords.setPayFee(arrivalAmount);
            bizWithdrawalRecords.setArrivalAmount(aizWithdrawalMoney.getAmount().subtract(arrivalAmount).setScale(2,BigDecimal.ROUND_DOWN));
            bizWithdrawalRecords.setWalletAmount(aizWithdrawalMoneyData.getAmount().subtract(aizWithdrawalMoney.getAmount()));
            bizWithdrawalRecords.setWithdrawalTime(new Date());
            bizWithdrawalRecords.setRemark(user.getDeptId() == 100L?"安心付-闯业" : user.getDeptId() == 101L?"安心付-伙伴":"安心付-乐富");
            //保存记录
            if(iBizWithdrawalRecordsService.saveOrUpdate(bizWithdrawalRecords)){// 保存账单
                aizWithdrawalMoneyData.setChannelId(aizWithdrawalMoney.getChannelId());
                bizWalletNewMapper.updateAizWithdrawalWalletByUserId(aizWithdrawalMoneyData);//修改钱包余额
                return AjaxResult.success("提现已提交,待审核","true");
            }else{
                return AjaxResult.error("提现失败","false");
            }
        }else{
            return executeWithdrawalAizWithdrawalWallet(aizWithdrawalMoney);
        }
    }

    @Override
    public void updateWalletUserNameByUserId(Long userId, String nickName) {
        bizWalletNewMapper.updateWalletUserNameByUserId(userId, nickName);
    }

    @Override
    public void updateWithdrawalWallet(AizWithdrawalWallet aizWithdrawalWallet) {
        bizWalletNewMapper.updateWithdrawalWallet(aizWithdrawalWallet);
    }

    @Override
    public AjaxResult totalWalletBalance(BizWalletNew bizWalletNew) {
        Long userId = bizWalletNew.getUserId();
        // 分润以及机具返现钱包
        BigDecimal walletBalance = bizWalletNewMapper.getWalletBalance(userId);
        // 奖励钱包
        BigDecimal rewardBalance = bizWalletNewMapper.getRewardBalance(userId);
        // 扣款钱包
        BigDecimal deductionBalance =  bizWalletNewMapper.getDeductionBalance(userId);
        BigDecimal balance = walletBalance.add(rewardBalance);
        String deductionBalanceStr = "";
        if(deductionBalance.compareTo(BigDecimal.ZERO) > 0){
            deductionBalanceStr = "-"+deductionBalance;
        }else{
            deductionBalanceStr = ""+deductionBalance;
        }
        String resStr = balance+"("+deductionBalanceStr+")";
        return AjaxResult.success("钱包总额",resStr);
    }

    @Override
    public BizWalletNew getWalletNewByUserIdAndChannel(Long userId, Long channelId) {
        return bizWalletNewMapper.getWalletNewByUserIdAndChannel(userId,channelId);
    }

    @Override
    public AizWithdrawalWallet getWithdrawalWalletByUserIdAndChannelId(Long userId, Long channelId) {
        return bizWalletNewMapper.getWithdrawalWalletByUserIdAndChannelId(userId,channelId);
    }

    @Override
    public void testShareWithdrawal(BizWithdrawalRecords bizWithdrawalRecords) {
        bizWithdrawalRecords = iBizWithdrawalRecordsService.getById(bizWithdrawalRecords.getId());
        bizWithdrawalRecordsServiceImpl.executeMerchantWallet(bizWithdrawalRecords);
    }

    // 非闯业 分润钱包提现
    public AjaxResult executeWithdrawalBizWalletNew(BizWalletNew bizWalletNewWithdrawal, BizWalletNew bizWalletData){
        //查看是否签约
        String signRes = checkIsSign(bizWalletData.getUserId());
        if("SUCCESS".equals(signRes)){
            return executePaymentBizWalletNewBefore(bizWalletNewWithdrawal,bizWalletData);
        }else{
            return AjaxResult.error("签约失败"+signRes,"false");
        }

    }
    // 非闯业 奖励钱包提现
    public AjaxResult executeWithdrawalAizWithdrawalWallet(AizWithdrawalWallet aizWithdrawalMoney){
        //查看是否签约
        String signRes = checkIsSign(aizWithdrawalMoney.getUserId());
        if("SUCCESS".equals(signRes)){
            return executePaymentAizWithdrawalWalletBefore(aizWithdrawalMoney);
        }else{
            return AjaxResult.error("签约失败"+signRes,"false");
        }
    }

    public AjaxResult executePaymentAizWithdrawalWalletBefore (AizWithdrawalWallet aizWithdrawalMoney){
        AizWithdrawalWallet aizWithdrawalMoneyData =
                bizWalletNewMapper.getWithdrawalWalletByUserId(aizWithdrawalMoney.getUserId(),aizWithdrawalMoney.getChannelId());
        if(aizWithdrawalMoneyData == null){
            return AjaxResult.error("暂无奖励钱包,请联系代理");
        }
        if(aizWithdrawalMoney.getAmount().compareTo(aizWithdrawalMoneyData.getAmount()) > 0){
            return AjaxResult.error("奖励账户余额不足,请重新输入");
        }
        //扣除提现金额
        aizWithdrawalMoneyData.setAmount(aizWithdrawalMoneyData.getAmount().subtract(aizWithdrawalMoney.getAmount()));
        // 保存提现记录
        BizWithdrawalRecords bizWithdrawalRecords = new BizWithdrawalRecords();
        bizWithdrawalRecords.setUserId(aizWithdrawalMoney.getUserId());
        SysUser user = iSysUserService.selectUserById(aizWithdrawalMoney.getUserId());
        bizWithdrawalRecords.setUserName(user.getNickName());
        bizWithdrawalRecords.setMerchPhone(user.getPhonenumber());
        bizWithdrawalRecords.setChannelId(aizWithdrawalMoney.getChannelId());
        BizMerchant bizMerchant = iBizMerchantService.getMerchantByUserId(aizWithdrawalMoney.getUserId());
        BizMicroInfo bizMicroInfo = iBizMicroInfoService.getBizMicroInfoByMerchId(bizMerchant.getMerchId());
        bizWithdrawalRecords.setWithdrawalName(bizMicroInfo.getMerchIdcardName());
        bizWithdrawalRecords.setWithdrawalAccount(bizMicroInfo.getMerchBankCardno());
        bizWithdrawalRecords.setWithdrawalType("3");//1 结算账户 2 机具返现 3 奖励
        bizWithdrawalRecords.setWithdrawalAmount(aizWithdrawalMoney.getAmount());
        BizChannel bizChannel = bizPosMachineMapper.getChannelByChannelId(aizWithdrawalMoney.getChannelId().toString());
        bizWithdrawalRecords.setChannelName(bizChannel.getChannelName());
        WithdrawalRateTemplate withdrawalRateTemplate = bizWithdrawalRecordsMapper.getDefaultWithdrawalRateTemplate();
        BigDecimal rate= withdrawalRateTemplate.getProfitRate();
        BigDecimal fee = withdrawalRateTemplate.getProfitFee();
        // 手续费
        BigDecimal arrivalAmount = aizWithdrawalMoney.getAmount().multiply(rate).setScale(2,BigDecimal.ROUND_DOWN).add(fee);
        bizWithdrawalRecords.setPayFee(arrivalAmount);
        bizWithdrawalRecords.setArrivalAmount(aizWithdrawalMoney.getAmount().subtract(arrivalAmount).setScale(2,BigDecimal.ROUND_DOWN));
        bizWithdrawalRecords.setWalletAmount(aizWithdrawalMoneyData.getAmount().subtract(aizWithdrawalMoney.getAmount()));
        bizWithdrawalRecords.setWithdrawalTime(new Date());
        bizWithdrawalRecords.setRemark(user.getDeptId() == 100L?"安心付-闯业" : user.getDeptId() == 101L?"安心付-伙伴":"安心付-乐富");
        String str= "HB";
        if(user.getDeptId() == 102L){
            str = "LF";
        }
        String natchno=str+System.currentTimeMillis()+""+String.format("%04d",new Random().nextInt(9999));
        bizWithdrawalRecords.setOrderNo(natchno);
        //保存记录
        if(iBizWithdrawalRecordsService.saveOrUpdate(bizWithdrawalRecords)){// 保存账单
            aizWithdrawalMoneyData.setChannelId(aizWithdrawalMoney.getChannelId());
            bizWalletNewMapper.updateAizWithdrawalWalletByUserId(aizWithdrawalMoneyData);//修改钱包余额
//            SysUser sysUser = iSysUserService.selectUserById(aizWithdrawalMoney.getUserId());
            return executePaymentAfter(natchno,bizMerchant.getMerchId(),bizWithdrawalRecords.getArrivalAmount().toString(),user.getDeptId().toString());
        }else{
            return AjaxResult.error("提现失败","false");
        }
    }


    public AjaxResult executePaymentBizWalletNewBefore(BizWalletNew bizWalletNewWithdrawal, BizWalletNew bizWalletData) {
        if("1".equals(bizWalletNewWithdrawal.getVar1())){
            if(bizWalletNewWithdrawal.getWithdrawalAmount().compareTo(bizWalletData.getProfitAmount()) > 0){
                return AjaxResult.error("分润账户余额不足,请重新输入","false");
            }
        }else{
            if(bizWalletNewWithdrawal.getWithdrawalAmount().compareTo(bizWalletData.getRewardAmount()) > 0){
                return AjaxResult.error("奖励账户余额不足,请重新输入","false");
            }
        }
        BizWithdrawalRecords bizWithdrawalRecords = new BizWithdrawalRecords();
        bizWithdrawalRecords.setChannelId(bizWalletData.getChannelId());
        bizWithdrawalRecords.setChannelName(bizWalletData.getChannelName());
        bizWithdrawalRecords.setUserId(bizWalletData.getUserId());
        SysUser user = iSysUserService.selectUserById(bizWalletData.getUserId());
        bizWithdrawalRecords.setMerchPhone(user.getPhonenumber());
        bizWithdrawalRecords.setUserName(user.getNickName());
        BizMerchant bizMerchant = iBizMerchantService.getMerchantByUserId(bizWalletData.getUserId());
        BizMicroInfo bizMicroInfo = iBizMicroInfoService.getBizMicroInfoByMerchId(bizMerchant.getMerchId());
        bizWithdrawalRecords.setWithdrawalName(bizMicroInfo.getMerchIdcardName());
        bizWithdrawalRecords.setWithdrawalAccount(bizMicroInfo.getMerchBankCardno());
        bizWithdrawalRecords.setWithdrawalType(bizWalletNewWithdrawal.getVar1());//1 结算账户 2  奖励账户
        bizWithdrawalRecords.setWithdrawalAmount(bizWalletNewWithdrawal.getWithdrawalAmount());
        WithdrawalRateTemplate withdrawalRateTemplate = bizWithdrawalRecordsMapper.getDefaultWithdrawalRateTemplate();
        BigDecimal rate= BigDecimal.ZERO;
        BigDecimal fee = BigDecimal.ZERO;
        if("1".equals(bizWalletNewWithdrawal.getVar1())){
            rate = withdrawalRateTemplate.getProfitRate().subtract(bizMerchant.getWithdrawalRate());
            fee = withdrawalRateTemplate.getProfitFee().subtract(bizMerchant.getWithdrawalFee());
            bizWalletData.setProfitAmount(bizWalletData.getProfitAmount().subtract(bizWalletNewWithdrawal.getWithdrawalAmount()).setScale(2,BigDecimal.ROUND_DOWN));
        }else{
            rate = withdrawalRateTemplate.getRewardRate().subtract(bizMerchant.getRewardWithdrawalRate());
            fee = withdrawalRateTemplate.getRewardFee().subtract(bizMerchant.getRewardWithdrawalFee());
            bizWalletData.setRewardAmount(bizWalletData.getRewardAmount().subtract(bizWalletNewWithdrawal.getWithdrawalAmount()).setScale(2,BigDecimal.ROUND_DOWN));
        }
        bizWalletData.setWalletAmount(bizWalletData.getProfitAmount().add(bizWalletData.getRewardAmount()).setScale(2,BigDecimal.ROUND_DOWN));
        // 手续费
        BigDecimal arrivalAmount = bizWalletNewWithdrawal.getWithdrawalAmount().multiply(rate).setScale(2,BigDecimal.ROUND_DOWN).add(fee);
        bizWithdrawalRecords.setPayFee(arrivalAmount);
        bizWithdrawalRecords.setArrivalAmount(bizWalletNewWithdrawal.getWithdrawalAmount().subtract(arrivalAmount).setScale(2,BigDecimal.ROUND_DOWN));
        bizWithdrawalRecords.setWalletAmount(bizWalletData.getWalletAmount());
        bizWithdrawalRecords.setWithdrawalTime(new Date());
        //处理钱包
        bizWalletData.setWithdrawalAmount(bizWalletData.getWithdrawalAmount().add(bizWalletNewWithdrawal.getWithdrawalAmount()).setScale(2,BigDecimal.ROUND_DOWN));
        bizWalletData.setWithdrawalServiceAmount(bizWalletData.getWithdrawalServiceAmount().add(arrivalAmount).setScale(2,BigDecimal.ROUND_DOWN));
        // 做关联   id
        String uuid = IdWorker.getIdStr();
        bizWithdrawalRecords.setVar2(uuid);
        bizWithdrawalRecords.setRemark(user.getDeptId() == 100L?"安心付-闯业" : user.getDeptId() == 101L?"安心付-伙伴":"安心付-乐富");
        String str= "HB";
        if(user.getDeptId() == 102L){
            str = "LF";
        }
        String natchno=str+System.currentTimeMillis()+""+String.format("%04d",new Random().nextInt(9999));
        bizWithdrawalRecords.setOrderNo(natchno);
        if(iBizWithdrawalRecordsService.saveOrUpdate(bizWithdrawalRecords)){ //保存记录
            this.saveOrUpdate(bizWalletData);//保存钱包
//            SysUser sysUser = iSysUserService.selectUserById(bizWalletData.getUserId());
            return executePaymentAfter(natchno,bizMerchant.getMerchId(),bizWithdrawalRecords.getArrivalAmount().toString(),user.getDeptId().toString());
        }else{
            return AjaxResult.error("提现失败","false");
        }
    }



    public AjaxResult executePaymentAfter(String natchno,Long merchId,String orderAmt,String deptId) {
        BizMicroInfo bizMicroInfoByMerchId = bizMicroInfoService.getBizMicroInfoByMerchId(merchId);
        AjaxResult ajaxResult=AjaxResult.success("单笔对私提现");

        /******************调用接口*************************/
        BatchPayment req = new BatchPayment();
        req.setBatchNo(natchno);
        //查询部门
        String  batchNo = cashoutRecordsService.getPathNoEnable();
        //获取数据库 enable为1 的可用数据
        System.out.println("新代付提现   batchNo:  "+batchNo);
        req.setPathNo(batchNo);
        req.setTotalAmount(orderAmt);
        req.setTotalNum("1");
        List<BatchPaymentList> list = new ArrayList<>();
        BatchPaymentList order = new BatchPaymentList();
        order.setOrderId(IdGen.uuid());
        order.setCardId(bizMicroInfoByMerchId.getMerchIdcard());
        order.setCardNo(bizMicroInfoByMerchId.getMerchBankCardno());
        order.setPayAmount(orderAmt);
        order.setPhoneNo(bizMicroInfoByMerchId.getMerchBankMobile());
        order.setRealName(bizMicroInfoByMerchId.getMerchIdcardName());
        String notifyUrl = "http://49.233.32.100:9091/pos/v1/merApi/notifyPaymentHb";
        if("102".equals(deptId)){
            notifyUrl = "http://49.233.32.100:9091/pos/v1/merApi/notifyPaymentLf";
        }
        order.setOrderExt1(notifyUrl);
        list.add(order);
        req.setPayInfos(list);
        //根据部分查代付主体
        BizBehalfPayment bizBehalfPayment = bizMicroInfoService.getBehalfPaymentByDeptId(deptId);
        Map<String, Object> hqyResultMap = HqyApiUtilsV2.callHqyMerApi(UUID.randomUUID().toString(), HqyMerFunctionEnumsV2.BATCH_PAYMENT.getCode(), req,bizBehalfPayment);
        JSONObject obj =JSONObject.parseObject(hqyResultMap.get("result").toString());
        BizWithdrawalRecords bizWithdrawalRecords = bizWithdrawalRecordsMapper.selectByOrderId(natchno);
        if("0".equals(obj.getString("businessStatus"))) {//受理成功
            ajaxResult = AjaxResult.success("提现成功，请关注回调接口。");
            ajaxResult.put("data", true);
            bizWithdrawalRecords.setPayStatus("0");// 进行中
            iBizWithdrawalRecordsService.saveOrUpdate(bizWithdrawalRecords);
            return ajaxResult;
        }else{
            // 走驳回
            // 钱包退回金额
            if("1".equals(bizWithdrawalRecords.getPayStatus()) || "2".equals(bizWithdrawalRecords.getPayStatus())){
                // 成功或已退回状态 不再退回钱包
                ajaxResult = AjaxResult.success("提现失败");
                ajaxResult.put("data", false);
                return ajaxResult;
            }
            System.out.println(bizWithdrawalRecords.getUserId()+"提现失败"+bizWithdrawalRecords);
            if("3".equals(bizWithdrawalRecords.getWithdrawalType())){// 奖励钱包
                AizWithdrawalWallet aizWithdrawalWallet =
                        this.getWithdrawalWalletByUserIdAndChannelId(
                                bizWithdrawalRecords.getUserId(),bizWithdrawalRecords.getChannelId());
                aizWithdrawalWallet.setAmount(aizWithdrawalWallet.getAmount().add(bizWithdrawalRecords.getWithdrawalAmount()));
                this.updateAizWithdrawalWalletByUserId(aizWithdrawalWallet);
                System.out.println(bizWithdrawalRecords.getUserId()+"提现失败回至奖励钱包"+bizWithdrawalRecords.getWithdrawalAmount()+"元");
            }else{// 分润和返现钱包
                BizWalletNew bizWalletNew =
                        this.getWalletNewByUserIdAndChannel(
                                bizWithdrawalRecords.getUserId(),bizWithdrawalRecords.getChannelId());
                if("1".equals(bizWithdrawalRecords.getWithdrawalType())){// 分润钱包
                    bizWalletNew.setProfitAmount(bizWalletNew.getProfitAmount().add(bizWithdrawalRecords.getWithdrawalAmount()));
                }else{// 返现钱包
                    bizWalletNew.setRewardAmount(bizWalletNew.getRewardAmount().add(bizWithdrawalRecords.getWithdrawalAmount()));
                }
                bizWalletNew.setWalletAmount(bizWalletNew.getWalletAmount().add(bizWithdrawalRecords.getWithdrawalAmount()));
                this.saveOrUpdate(bizWalletNew);
                System.out.println(bizWithdrawalRecords.getUserId()+"提现失败回至分润返现钱包"+bizWithdrawalRecords.getWithdrawalAmount()+"元");
            }
            bizWithdrawalRecords.setPayStatus("2");// 失败
            iBizWithdrawalRecordsService.saveOrUpdate(bizWithdrawalRecords);
            ajaxResult = AjaxResult.success("提现失败");
            ajaxResult.put("data", false);
            return ajaxResult;
        }
    }



    public String checkIsSign(Long userId){
        BizMerchant bizMerchant = new BizMerchant();
        bizMerchant.setUserId(userId);
        BizMerchantReceiver bizMerchantReceiver = iBizMerchantService.selectBizMerchantReceiver(bizMerchant);
        if(bizMerchantReceiver != null && "2".equals(bizMerchantReceiver.getContractStatus())){
            return "SUCCESS";
        }
        String merchId = iBizMerchantService.selectMerchId(bizMerchant.getUserId().toString());
        BizMicroInfo bizMicroInfoByMerchId = bizMicroInfoService.getBizMicroInfoByMerchId(Long.parseLong(merchId));
        SysUser sysUser = iSysUserService.selectUserById(userId);
        return goSign(bizMicroInfoByMerchId,bizMerchant.getUserId(),bizMerchantReceiver,sysUser.getDeptId().toString());
    }


    private String goSign(BizMicroInfo bizMicroInfoByMerchId,Long userId,BizMerchantReceiver bizMerchantReceiver1,String deptId){
        BizMerchantReceiver bizMerchantReceiver =  new BizMerchantReceiver();
        UserSign userSign = new UserSign();
        userSign.setRealName(bizMicroInfoByMerchId.getMerchIdcardName());
        userSign.setCardId(bizMicroInfoByMerchId.getMerchIdcard());
        userSign.setPhoneNo(bizMicroInfoByMerchId.getMerchBankMobile());
        bizMerchantReceiver.setMerchName(bizMicroInfoByMerchId.getMerchIdcardName());
        bizMerchantReceiver.setMerchIdcard(bizMicroInfoByMerchId.getMerchIdcard());
        bizMerchantReceiver.setMerchBankMobile(bizMicroInfoByMerchId.getMerchBankMobile());
        bizMerchantReceiver.setMerchBankCardno(bizMicroInfoByMerchId.getMerchBankCardno());
        bizMerchantReceiver.setMerchId(bizMicroInfoByMerchId.getMerchId());
        bizMerchantReceiver.setUserId(userId);
        //根据部门查代付主体
        BizBehalfPayment bizBehalfPayment = bizMicroInfoService.getBehalfPaymentByDeptId(deptId);
        Map<String, Object> map = HqyApiUtilsV2.callHqyMerApi(UUID.randomUUID().toString(),
                HqyMerFunctionEnumsV2.USER_SIGN.getCode(),
                bizBehalfPayment.getBehalfCode(),
                userSign,bizBehalfPayment);
        JSONObject obj =JSONObject.parseObject(map.get("result").toString());
        System.out.println("{}|reqeust->签约:{}"+map.toString());
        if(bizMerchantReceiver1!=null){
            bizMerchantReceiver.setId(bizMerchantReceiver1.getId());
        }
        if("0".equals(obj.get("businessStatus"))){
            //签约成功
            bizMerchantReceiver.setContractStatus("2");
            iBizMerchantReceiverService.saveOrUpdate(bizMerchantReceiver);
            return "SUCCESS";
        }else{
            //签约失败
            bizMerchantReceiver.setContractStatus("1");
            String msg = "";
            if("".equals(obj.get("explain")) || null == obj.get("explain") ){
                if("".equals(obj.get("message")) || null == obj.get("message")){
                    msg = "请联系服务商";
                }else{
                    msg = obj.get("message").toString();
                }
            }else{
                msg = obj.get("explain").toString();
            }
            bizMerchantReceiver.setErroMessage(msg);
            iBizMerchantReceiverService.saveOrUpdate(bizMerchantReceiver);
            return msg;
        }
    }


}
